let STR1 = 'newjourney';
let STR2 = 'hiworld';
let STR3 = 'G';
let sm2PubKey = '041BF637DEC9926F29394AE0B28FE71EDAB1902DEF0F29F87F135B8277E863C6B22636985462DF87B0EE12BA332F1DEF3CBBA6CAE51FE33A2474797AE7800109F3';
let sm2PriKey = '1AC16729848D7D9E2CC36E1B215E916DEBD9E4569E81686B8DDFA25973E93554';
/**
 * 传输加密
 * @param {明文} plaintext 
 * @returns 
 */
function gmTransmissionEncrypt(plaintext) {
    //时间戳
    var time = Date.parse(new Date());
    var dataBy = Hex.utf8StrToBytes(plaintext + STR1 + time);
    //SM3（结果+STR1+时间戳）
    var sm3 = new SM3Digest();
    sm3.update(dataBy, 0, dataBy.length);//数据很多的话，可以分多次update
    var sm3Hash = sm3.doFinal();//得到的数据是个byte数组
    var digestHex = Hex.encode(sm3Hash, 0, sm3Hash.length);//编码成16进制可见字符
    //SM4.encrypt（（结果+STR1+时间戳+STR2+SM3（结果+STR1+时间戳））
    var sm4Key = generateKey();
    var sm4 = new SM4();
    var splicingStr = sm4.encrypt_cbc(Hex.decode(sm4Key), Hex.decode(sm4Key), Hex.utf8StrToBytes(plaintext + STR1 + time + STR2 + digestHex));
    //SM2.encrypt（SM4KEY）
    var sm2 = new SM2();
    var sm4k = sm2.encrypt(sm2PubKey, sm4Key);//函数输入输出都是16进制数据
    //结果：SM4.encrypt（结果+STR1+时间戳+STR2+SM3（结果+STR1+时间戳））+STR3+SM2.encrypt（SM4KEY）即：splicingStr+str3+sm4key
    return Hex.encode(splicingStr, 0, splicingStr.length) + STR3 + sm4k;
}

/**
 * 传输解密
 * @param {密文} cipherText 
 */
function gmTransmissionDecrypt(cipherText) {
    // var result = {};
    //拼接字符串，即SM4.encrypt（结果+STR1+时间戳+STR2+SM3（结果+STR1+时间戳））
    var splicingStr = cipherText.split(STR3)[0];
    //sm2加密过的sm4的密钥
    var sm4key = cipherText.split(STR3)[1];
    //获取sm4的密钥
    var sm2 = new SM2();
    var sm4SecretKey = sm2.decrypt(sm2PriKey, sm4key);
    //解密splicingStr，得到：结果+STR1+时间戳+STR2+SM3（结果+STR1+时间戳）
    var sm4 = new SM4();
    var splicingStr0 = Hex.bytesToUtf8Str(sm4.decrypt_cbc(Hex.decode(sm4SecretKey), Hex.decode(sm4SecretKey), Hex.decode(splicingStr)));
    //对splicingStr0：结果+STR1+时间戳+STR2+SM3（结果+STR1+时间戳），进行拆分
    var resultStr = splicingStr0.split(STR2)[0];
    var digestHex = splicingStr0.split(STR2)[1];
    //判断完整性，如果摘要对比一致，返回结果
    //SM3（结果+STR1+时间戳）
    var sm3 = new SM3Digest();
    var dataBy = Hex.utf8StrToBytes(resultStr);
    sm3.update(dataBy, 0, dataBy.length);//数据很多的话，可以分多次update
    var sm3Hash = sm3.doFinal();//得到的数据是个byte数组
    var digestHex2 = Hex.encode(sm3Hash, 0, sm3Hash.length);//编码成16进制可见字符
    if (digestHex.trim() === digestHex2.trim()) {
        // result['cipherText'] = resultStr.split(STR1)[0];
        // return result;
        return resultStr.split(STR1)[0];
    } else {
        // return result;
        return null;
    }
}
/**
 * 生成密钥
 */
function generateKey() {
    var rng = new SecureRandom();
    var keyBit = new BigInteger(128, rng);
    while (keyBit.bitLength() < 128) {
        keyBit = new BigInteger(128, rng);
    }
    var key = ("0000000000" + keyBit.toString(16)).slice(- 128 / 4);
    return key.toUpperCase();
}